//
//  ProductReviewViewController.m
//  cherryproduct
//
//  Created by umessage on 14-8-18.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "ProductReviewViewController.h"
#import "SMAlbumViewController.h"
#import "SMImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "AGEmojiKeyboard/AGEmojiKeyBoardView.h"
#import "AGEmojiKeyboard/AGEmojiPageView.h"
#import "AGFaceView.h"

@interface ProductReviewViewController ()<UICollectionViewDelegate, UICollectionViewDataSource,AGEmojiKeyboardViewDelegate, AGEmojiKeyboardViewDataSource, AGDELGET_EMOJ_SELECT>
{
    UICollectionView * m_collectionView;
    
//    AGEmojiKeyboardView *emojiKeyboardView;
    
    AGFaceView * face_view;
}

@property(nonatomic, strong) UITextView * textView;
@property(nonatomic, strong) UIView * view_function;

//@property(nonatomic, strong) UIButton * btn_click;
@property(nonatomic, strong) UIButton * btn_click0;
@property(nonatomic, strong) UIButton * btn_click1;
@property(nonatomic, strong) UIButton * btn_click2;
//@property(nonatomic, strong) UIView * btn_view_open;
//@property(nonatomic, strong) UIView * btn_view_close;

@property(nonatomic, strong) UILabel * label_address;
@property(nonatomic, strong) UILabel * label_select_photo;

@property(nonatomic, strong) UILabel * label_press;
@property(nonatomic, strong) UIView_PXO_Face * view_for_face;

@property(nonatomic, assign) NSInteger select_star0;
@property(nonatomic, assign) NSInteger select_star1;
@property(nonatomic, assign) NSInteger select_star2;
@property(nonatomic, assign) NSInteger select_star3;

@property(nonatomic, strong) NSMutableArray * array_select;

//...
@property(nonatomic, strong) UILabel * label_placeholder;
@property(nonatomic, strong) UIScrollView * base_scrollview;

@property (nonatomic, strong) ALAssetsLibrary * assetsLibrary;
@property (nonatomic, strong) NSMutableArray * array_assert;

@property (nonatomic, assign) BOOL m_b_have_load_img;

@end

@implementation ProductReviewViewController

- (NSMutableArray*)array_select
{
    if (_array_select==nil) {
        _array_select =[[NSMutableArray alloc] initWithCapacity:8];
    }
    return _array_select;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

/*
-(void)initviewstyle
{
    int y=10;
    UIImage* upimage = [UIImage imageNamed:@"productreviewsup"];
    UIImage* downimage = [UIImage imageNamed:@"productreviewsdown"];
    UIImageView* imageview ; //分割线
    for(int i = 0 ; i < 4 ;i++)
    {
        UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, y, 95, 16)];
        label.textColor = [UIColor blackColor];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentRight;
        label.font = [UIFont systemFontOfSize:16];
        if(i==0) {
            label.text = @"好用指数";
        } else if (i==1) {
            label.text = @"使用度指数";
        } else if (i==2) {
            label.text = @"性价比指数";
        } else {
            label.text = @"安全性指数";
        }
        
        int x = label.frame.origin.x+label.frame.size.width+15;//butt哼左边
        NSMutableArray* array = [[NSMutableArray alloc] init];
        for(int j = 0 ; j < 5 ;j++)
        {
            UIImageView* imageviewstar = [[UIImageView alloc] initWithFrame:CGRectMake(x, label.frame.origin.y+(label.frame.size.height-upimage.size.height)/2, upimage.size.width, upimage.size.height)];
            imageviewstar.backgroundColor = [UIColor clearColor];
            imageviewstar.tag = j+(100+100*i); //100起步依次向下最多到500标记
            imageview.userInteractionEnabled = YES;
            if(j==4)
            {
                imageviewstar.image = downimage;
                
            }
            else
            {
                imageviewstar.image = upimage;

            }
            [self.myView addSubview:imageviewstar]; //添加评分按钮
            x = x + imageviewstar.frame.size.width+15;
            
            NSMutableDictionary* dic = [[NSMutableDictionary alloc] init];
            [dic setObject:[NSNumber numberWithInt:imageviewstar.frame.origin.x+imageviewstar.frame.size.width] forKey:@"starx"];
            [dic setObject:[NSNumber numberWithInt:imageviewstar.frame.origin.y+imageviewstar.frame.size.height] forKey:@"stary"];
            [dic setObject:[NSNumber numberWithInt:4] forKey:@"star"];
            [dic setObject:[NSNumber numberWithInt:imageviewstar.tag] forKey:@"startag"];
            [array addObject:dic];
        }
        [arraystar addObject:array];
        
        [self.myView addSubview:label]; //添加评级说明
        y = y+ label.frame.size.height+10;
        
        if(i == 3)
        {
            starty = label.frame.origin.y+label.frame.size.height;
            imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10,
                                                                      label.frame.origin.y+label.frame.size.height+10,
                                                                      self.myView.frame.size.width-20,
                                                                      0.5)];
            imageview.backgroundColor = [UIColor blackColor];
            [self.myView addSubview:imageview];//添加分割线
        }
    }
    
//    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.myView.frame.size.width, self.myView.frame.size.height)];
//    view.backgroundColor = [UIColor whiteColor];
//    view.tag = 9123;
//    view.hidden = YES;
//    [self.myView addSubview:view];
    
    
//    scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, imageview.frame.origin.y+imageview.frame.size.height+5, self.myView.frame.size.width, self.myView.frame.size.height-(imageview.frame.origin.y+imageview.frame.size.height+5))];
//    scrollview.backgroundColor = [UIColor whiteColor];
//    scrollview.contentSize = CGSizeMake(scrollview.frame.size.width,scrollview.frame.size.height);
//    [self.myView addSubview:scrollview];
    
    CGFloat width = self.myView.frame.size.width;
    CGFloat height = self.myView.frame.size.height;
    
    textview = [[UITextView alloc] initWithFrame:CGRectMake(0, y, width, height-y)];
    textview.font = [UIFont systemFontOfSize:12];
    textview.textColor = [UIColor blackColor];
    textview.backgroundColor = [UIColor orangeColor];
    textview.returnKeyType = UIReturnKeyDone;//返回键的类型
    textview.keyboardType = UIKeyboardTypeDefault;//键盘类型
    textview.scrollEnabled = NO;//是否可以拖动
    textview.userInteractionEnabled = YES;
    textview.delegate = self;
    [self.myView addSubview:textview];//加入到整个页面中
    
    self.label_placeholder = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 100, 30)];
    self.label_placeholder.backgroundColor=[UIColor clearColor];
    self.label_placeholder.textColor=[UIColor grayColor];
    self.label_placeholder.font = [UIFont systemFontOfSize:12];
    self.label_placeholder.text=@"请写评论...";
    [textview addSubview:self.label_placeholder];
}
*/
#pragma mark -
#pragma mark UITextViewDelegate


#pragma mark -
#pragma mark SOGA

/*
-(void)textviewbuttonreview //建立照相机试图
{
    UIImage* imageback = [UIImage imageNamed:@"backviewreview"];
    UIImageView* imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.myView.frame.size.height-textviewboardheight-imageback.size.height, self.myView.frame.size.width, imageback.size.height)];
    imageview.userInteractionEnabled = YES;
    imageview.image = imageback;
    imageview.tag = 7618;
    [self.myView addSubview:imageview];
    
    int x = 5;
    UIImage* imagecar = [UIImage imageNamed:@"carmerreview"];
    UIImage* imageface = [UIImage imageNamed:@"facereview"];
    UIImage* imagelib = [UIImage imageNamed:@"libreview"];
    for(int i = 0 ; i < 3 ; i ++)
    {
        UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, 40, 40)];
        button.tag = 931+i;
        [button addTarget:self action:@selector(textviewboardreview:) forControlEvents:UIControlEventTouchUpInside];
        int temp= 0;
        if(i==0)
        {
            [button setBackgroundImage:imagecar forState:UIControlStateNormal];
            button.frame = CGRectMake(x,(imageview.frame.size.height-imagecar.size.height)/2, imagecar.size.width, imagecar.size.height);
            temp = x+imagecar.size.width+20;
        }
        else if(i==1)
        {
            [button setBackgroundImage:imagelib forState:UIControlStateNormal];
            button.frame = CGRectMake(x,(imageview.frame.size.height-imagelib.size.height)/2, imagelib.size.width, imagelib.size.height);
            temp = x+imagelib.size.width+20;

        }
        else
        {
            [button setBackgroundImage:imageface forState:UIControlStateNormal];
            button.frame = CGRectMake(x,(imageview.frame.size.height-imageface.size.height)/2, imageface.size.width, imageface.size.height);
            temp = x+imageface.size.width+20;

        }
        
        [imageview addSubview:button];
        x = temp;
    }
}

-(void)textviewboardreview:(UIButton*)button
{
    int temp = button.tag-931;
    if(temp==0) //相机
    {
        if(faceimageview)
        {
            [faceimageview removeFromSuperview];
            faceimageview = nil;
        }

        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
        if (isCamera) {
            [textview resignFirstResponder];
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.view.tag = 1011;//相机
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePicker.delegate = self;
            // 编辑模式
            imagePicker.allowsEditing = YES;
            
            [self  presentViewController:imagePicker animated:YES completion:^{
            }];
        }
        else
        {
            [self showAlertView:@"温馨提示" subtitle:@"您的设备不支持此功能"];
        }

    }
    else if(temp==1) //图册
    {
        if(faceimageview)
        {
            [faceimageview removeFromSuperview];
            faceimageview = nil;
        }

        [textview resignFirstResponder];
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.view.tag = 1012;//相册
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        [self  presentViewController:imagePicker animated:YES completion:^{
        }];
        

    }
    else //表情
    {
        if(faceimageview)
        {
            [faceimageview removeFromSuperview];
            faceimageview = nil;
        }
        else
        {
            UIWindow* wind = [[UIApplication sharedApplication].windows objectAtIndex:[[UIApplication sharedApplication].windows count]-1];
            NSLog(@"%lf",wind.frame.size.height);
            faceimageview = [[UIfaceimageview alloc] initWithFrame:CGRectMake(0, wind.frame.size.height- textviewboardheight, self.myView.frame.size.width, textviewboardheight)];
            faceimageview.delegate = self;
            [wind addSubview:faceimageview];
        }
       
    }
}

-(void)UIfaceimageviewdelegate:(int)index
{
    [faceimageview removeFromSuperview];
    faceimageview = nil;
    if([textview.text isEqualToString:@"请输入评论内容……"])
    {
        textview.text = [NSString stringWithFormat:@"[qqface]%d[/qqface]",index];
    }
    else
    {
        NSMutableString* string = [[NSMutableString alloc] init];
        [string appendString:textview.text];
        [string appendFormat:@"[qqface]%d[/qqface]",index];
        textview.text = string;
    }
    
    [self textViewDidChange:textview];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"%@", info);
    UIImage *image = nil;
    
    if(picker.view.tag == 1011) //相机
    {
        image = [info objectForKey:UIImagePickerControllerEditedImage];

    }
    else //图片
    {
        image = [info objectForKey:UIImagePickerControllerOriginalImage];

    }
    
    CGSize size = [textview.text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(scrollview.frame.size.width-10, 999) lineBreakMode:NSLineBreakByWordWrapping];
    
    if(imageviewphoto)
    {
        imageviewphoto.image = image;
        imageviewphoto.frame = CGRectMake(5, size.height+20, 100, 100);
    }
    else
    {
        imageviewphoto = [[UIImageView alloc] init];
        imageviewphoto.frame = CGRectMake(5, size.height+20, 100, 100);
        imageviewphoto.image = image;
        imageviewphoto.backgroundColor = [UIColor redColor];
        [scrollview addSubview:imageviewphoto];
    }
    scrollview.contentSize = CGSizeMake(scrollview.frame.size.width, size.height+20+100);
    if(scrollview.frame.size.height<(size.height+20+100))
    {
        [scrollview setContentOffset:CGPointMake(scrollview.frame.size.width,  size.height+20+100-(scrollview.frame.size.height)+10) animated:NO];
    }
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}



- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
}

- (void) keyboardWasShown:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    textviewboardheight = keyboardSize.height;
    
    UIImage* imageback = [UIImage imageNamed:@"backviewreview"];

    if([self.myView viewWithTag:7618])
    {

        UIImageView* imageview = (UIImageView*)[self.myView viewWithTag:7618];
        imageview.frame = CGRectMake(0, self.myView.frame.size.height-textviewboardheight-imageback.size.height, self.myView.frame.size.width, imageback.size.height);
    }
    else
    {
        [self textviewbuttonreview];

    }
    
    maxtextviewheight = self.myView.frame.size.height-textviewboardheight-imageback.size.height-22;
    
    scrollview.frame = CGRectMake(0, 0, self.myView.frame.size.width, self.myView.frame.size.height-textviewboardheight-imageback.size.height);
    scrollview.contentSize = CGSizeMake(scrollview.frame.size.width, scrollview.frame.size.height);
    [self textViewDidBeginEditing:textview];
    

}
*/

#pragma mark -
#pragma mark SystemMethod

//-(void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
//    if(faceimageview)
//    {
//        [faceimageview removeFromSuperview];
//        faceimageview = nil;
//    }
//}

-(void)removetextviewbuttonreview //释放照相机试图
{
    [[self.myView viewWithTag:7618] removeFromSuperview];
}

-(BOOL)ispassupdate//验证可否通过要求
{
    BOOL ispass = YES;
    if(![dicparm objectForKey:@"4"])
    {
        ispass = NO;
        [self showAlertView:@"温馨提示" subtitle:@"请输入评论内容"];
    }
    return ispass;
}

/*
- (void)textViewDidBeginEditing:(UITextView *)textView
{

    if([textview.text isEqualToString:@"请输入评论内容……"])
    {
        textview.text = @"";
    }
    
    imageviewphoto.hidden = YES;
    UILabel* label = nil;
    textview.scrollEnabled = YES;//是否可以拖动
//    [self.myView viewWithTag:9123].hidden = NO;
    if([scrollview viewWithTag:1098])
    {
        label = (UILabel*)[scrollview viewWithTag:1098];
    }
    else
    {
        label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        label.textColor = [UIColor blackColor];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentRight;
        label.font = [UIFont systemFontOfSize:12];
        label.tag = 1098;
        [scrollview addSubview:label];//字数限制
    }
    if(scrollview.frame.origin.y!=0)
    {
        textviewy = scrollview.frame.origin.y;
    }
    
    CGSize size = CGSizeMake(0, 0);
    if([textview.text length])
    {
        size = [textview.text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(textview.frame.size.width-10, 999) lineBreakMode:UILineBreakModeWordWrap];
    }
    textview.frame = CGRectMake(0, 0, scrollview.frame.size.width, maxtextviewheight);
    if(size.height>maxtextviewheight)
    {
        [textview setContentOffset:CGPointMake(0, size.height-maxtextviewheight+10) animated:NO];
        size.height = maxtextviewheight;
    }
    label.frame = CGRectMake(0, size.height+10, textview.frame.size.width, 12);
    label.text = [NSString stringWithFormat:@"%d/500",[textview.text length]];
    

}
*/

/*
-(void)textViewDidEndEditing:(UITextView *)textView
{
    if(faceimageview)
    {
        [faceimageview removeFromSuperview];
        faceimageview = nil;
    }
    if([textview.text isEqualToString:@""])
    {
        textview.text = @"请输入评论内容……";
        [dicparm removeObjectForKey:@"4"];//移除评论文字

    }
    else
    {
        [dicparm setObject:textview.text forKey:@"4"];//添加评论文字
    }

//    [self.myView viewWithTag:9123].hidden = YES;
    [[scrollview viewWithTag:1098] removeFromSuperview];
    [self removetextviewbuttonreview];
    imageviewphoto.hidden = NO;
    textview.scrollEnabled = NO;//是否可以拖动
    
    CGSize size = [textview.text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(scrollview.frame.size.width-10, 999) lineBreakMode:NSLineBreakByWordWrapping];
    
    if(imageviewphoto)
    {
        imageviewphoto.frame = CGRectMake(5, size.height+20, 100, 100);
    }
    
    scrollview.frame = CGRectMake(0, textviewy, self.myView.frame.size.width,self.myView.frame.size.height-textviewy);
    textview.frame = CGRectMake(0, 0, scrollview.frame.size.width, scrollview.frame.size.height);
    if(imageviewphoto)
    {
        imageviewphoto.frame = CGRectMake(5, size.height+20, 100, 100);
        scrollview.contentSize = CGSizeMake(scrollview.frame.size.width,size.height+20+100);

    }
    else
    {
        scrollview.contentSize = CGSizeMake(scrollview.frame.size.width, size.height);

    }
    
    
}

-(BOOL) textView :(UITextView *) textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *) text
{
    if ([text isEqualToString:@"\n"])
    {
        [textview resignFirstResponder];
    }
    return YES;
}*/

//-(void)textViewDidChange:(UITextView *)textView
//{
//    
//    CGSize size = [textview.text sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(textview.frame.size.width-10, 999) lineBreakMode:UILineBreakModeWordWrap];
//    
//    UILabel*label = (UILabel*)[scrollview viewWithTag:1098];
//    if(size.height>maxtextviewheight)
//    {
//        size.height = maxtextviewheight;
//    }
//    label.frame = CGRectMake(0, size.height+10, textview.frame.size.width, 12);
//    label.text = [NSString stringWithFormat:@"%d/500",[textview.text length]];
//    
//    
//    if(textview.text.length>500)
//    {
//        [self showAlertView:@"温馨提示" subtitle:@"点评内容最多只可输入500字"];
//    }
//    else
//    {
//        ;
//    }
//    
//}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.textView) {
        [self.textView becomeFirstResponder];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:@"写评论"];
    [self addNavBarButton:RIGHT_SUBMENT];
    
    self.assetsLibrary = [[ALAssetsLibrary alloc] init];
    self.array_assert = [[NSMutableArray alloc] initWithCapacity:60];
    
    self.select_star0=4;
    self.select_star1=4;
    self.select_star2=4;
    self.select_star3=4;
    /*
    textviewtextheight = 0;
    arraystar = [[NSMutableArray alloc] init];
    dicparm = [[NSMutableDictionary alloc] init];
    [dicparm setObject:[NSNumber numberWithInt:3] forKey:@"0"];
    [dicparm setObject:[NSNumber numberWithInt:3] forKey:@"1"];
    [dicparm setObject:[NSNumber numberWithInt:3] forKey:@"2"];
    [dicparm setObject:[NSNumber numberWithInt:3] forKey:@"3"];

    self.myView.tag = 9832;
    [self initviewstyle];
    self.myView.backgroundColor = [UIColor whiteColor];
     */
    
    self.base_scrollview = [[UIScrollView alloc] initWithFrame:self.myView.bounds];
    [self.myView addSubview:self.base_scrollview];
    // Do any additional setup after loading the view from its nib.
    [self setBOSe];
    [self setRichText];
    
    [self.base_scrollview setContentSize:CGSizeMake(self.myView.frame.size.width, self.myView.frame.size.height+110)];
}


//-(void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
//    [self registerForKeyboardNotifications];
//}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event //点击输入框背景取消输入框
{
    UITouch* touch = [touches anyObject];
    if(([touch.view isKindOfClass:[textview class]]||[touch.view isKindOfClass:[UIButton class]]))
    {
        ;
    }
    else
    {
        [textview resignFirstResponder];

    }
    
    int x  = [touch locationInView:touch.view].x;
    int y = [touch locationInView:touch.view].y;
   

    if((touch.view.tag == 9832)&&(y<=starty)&&(y>0))
    {
       
        [self drawstarreview:x indexy:y];
    }
    

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* touch = [touches anyObject];

    int x  = [touch locationInView:touch.view].x;
    int y = [touch locationInView:touch.view].y;
    if((touch.view.tag == 9832)&&(y<=starty)&&(y>0))
    {
        [self drawstarreview:x indexy:y];
        
    }



}

-(void)drawstarreview:(int)x indexy:(int)y //评论星星
{
    NSLog(@"%d,%d",x,y);
    int indexy = -1; //纵坐标
    int indexx = -1; //heng坐标
    for(int i = 0 ; i < [arraystar count];i++) //找y
    {
        
        NSArray* array = [arraystar objectAtIndex:i];
        int stary = [[[array objectAtIndex:0] objectForKey:@"stary"] intValue];
        if(y<=stary)
        {
            indexy = i;
            break;
        }
    }
    NSArray* array;
    if(indexy>=0)
    {
       array = [arraystar objectAtIndex:indexy];
    }
    if(array)
    {
        for(int i = 0 ; i < [array count];i++) //找x
        {
            
            NSDictionary* dic = [array objectAtIndex:i];
            int starx = [[dic objectForKey:@"starx"] intValue];
            if(x<=starx)
            {
                indexx = i;
                break;
            }
        }
        
        NSLog(@"%d,%d",indexy,indexx);
        
        if(indexx>=0)
        {
            UIImage* upimage = [UIImage imageNamed:@"productreviewsup"];
            UIImage* downimage = [UIImage imageNamed:@"productreviewsdown"];
            for(int i = 0 ; i < 5 ; i++) //花星星
            {
                
                NSDictionary* dic = [array objectAtIndex:i];
                int tag = [[dic objectForKey:@"startag"] intValue];
                UIImageView* imageview = (UIImageView*)[self.myView viewWithTag:tag];
                if(i<= indexx)
                {
                    imageview.image = upimage;
                }
                else
                {
                    imageview.image = downimage;
                }
            }
            
            [dicparm setObject:[NSNumber numberWithInt:indexx] forKey:[NSString stringWithFormat:@"%d",indexy]];
            
        }
      
    }
    
}
*/

-(void)submentbuttondown:(UIButton*)button //发布
{
    if (self.textView.text==nil || [self.textView.text isEqualToString:@""]) {
        [self showAlertView:@"温馨提示" subtitle:@"请填写内容"];
        return;
    }

    NSMutableDictionary * dic = [[NSMutableDictionary alloc] initWithCapacity:5];
    [dic setObject:self.str_id forKey:@"id"];
    [dic setObject:[NSNumber numberWithInteger:self.select_star0] forKey:@"gooduse_exp"];
    [dic setObject:[NSNumber numberWithInteger:self.select_star1] forKey:@"costs_exp"];
    [dic setObject:[NSNumber numberWithInteger:self.select_star2] forKey:@"try_exp"];
    [dic setObject:[NSNumber numberWithInteger:self.select_star3] forKey:@"safety_exp"];
    [dic setObject:self.textView.text forKey:@"content"];
    
    /*
    [self.view startLoadingAnimation];
    [[HttpNewBaseService sharedClient] postRequestOperationAsset:@"goods_comment/comment"
                                                 paramDictionary:dic
                                                    onCompletion:^(NSString *responseString) {
                                                        [self.view stopLoadingAnimation];
                                                        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"评论成功!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                                        [alert show];
                                                    }
                                                         onError:^(NSError *error) {
                                                             [self.view stopLoadingAnimation];
                                                         }
                                                      onAnimated:YES
                                                       imagedata:self.array_select
                                                        imagekey:@""];
     */
    [self.view startLoadingAnimation];
    
    [[HttpNewBaseService sharedClient] POST:@"goods_comment/comment" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        //上传Image
        ALAsset * asset = nil;
        NSMutableString * str_name = nil;
        NSMutableString * str_name_png = nil;
        for (int i = 0; i < [self.array_select count]; i++) {
            asset = [self.array_select objectAtIndex:i];
//            UIImage * img = [UIImage imageWithCGImage:[asset thumbnail]];
//            NSData * data = UIImageJPEGRepresentation(img, 1.0f);
            
            ALAssetRepresentation * rep = [asset defaultRepresentation];
            unsigned long size = (unsigned long)rep.size;
            Byte *buffer = (Byte*)malloc(size);
            NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:size error:nil];
            NSData * data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
            //添加
            str_name = [NSMutableString stringWithFormat:@"img[%d]", i];
            str_name_png = [NSMutableString stringWithFormat:@"img[%d].png", i];
            [formData appendPartWithFileData:data
                                        name:str_name
                                    fileName:str_name_png
                                    mimeType:@"image/png"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view stopLoadingAnimation];
        
        NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
        if (status==1) {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                             message:@"评论成功!"
                                                            delegate:self
                                                   cancelButtonTitle:@"确定"
                                                   otherButtonTitles:nil, nil];
            [alert show];
        } else {
            [self showAlertView:@"温馨提示" subtitle:[responseObject objectForKey:@"message"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view stopLoadingAnimation];
        [self showAlertView:@"温馨提示" subtitle:@"网络断了!"];
    }];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (self.block_dismiss) {
        self.block_dismiss(0);
    }
    [self backButtonAction:nil];
}

#pragma mark -
#pragma mark Line
- (void)setBOSe
{
    CGFloat width = self.myView.frame.size.width;
    CGFloat height = self.myView.frame.size.height;
    
    NSArray * array = [[NSArray alloc] initWithObjects:
                       @"好用指数",
                       @"性价比指数",
                       @"使用频繁度指数",
                       @"安全性指数",nil];
    int y = 10;
    for (int i = 0; i < 4; i++) {
        UIView_Select_Star * star_view = [[UIView_Select_Star alloc] initWithFrame:CGRectMake(0, y, width, 25)
                                                                         withTitle:[array objectAtIndex:i]];
        star_view.delegate_click=self;
        star_view.tag=i;
        [self.base_scrollview addSubview:star_view];
        
        y += 30;
    }
    UIImageView * line = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"line"]];
    line.frame=CGRectMake(0, 129, width, 0.5);
    [self.base_scrollview addSubview:line];
    
    self.view_for_face = [[UIView_PXO_Face alloc] initWithFrame:CGRectMake(0,
                                                                           height-IOS_IPHONE_TXT_HEIGHT,
                                                                           width, IOS_IPHONE_TXT_HEIGHT)];
    self.view_for_face.hidden=YES;
    self.view_for_face.delegate_click=self;
    [self.myView addSubview:self.view_for_face];
}
- (void)doGroupIndex:(NSInteger)a starIndex:(NSInteger)b;
{
    if (a == 0) {
        self.select_star0=b;
    }
    if (a == 1) {
        self.select_star1=b;
    }
    if (a == 2) {
        self.select_star2=b;
    }
    if (a == 3) {
        self.select_star3=b;
    }
}
- (void)doClickFaceIndex:(NSString*)strFace
{
    self.label_press.hidden=YES;
    
    self.textView.text = [NSString stringWithFormat:@"%@%@", self.textView.text, strFace];

    {
        NSString * temp = self.textView.text;
        NSString * str_info = [NSString stringWithFormat:@"%d/500", temp.length];
        self.label_address.text=str_info;
    }
}
#pragma mark -
#pragma mark emoji
- (void)emojiKeyBoardView:(AGEmojiKeyboardView *)emojiKeyBoardView didUseEmoji:(NSString *)emoji {
    
    self.textView.text = [self.textView.text stringByAppendingString:emoji];
    
    if (self.textView.text.length > 0) {
        self.label_press.hidden=YES;
    } else {
        self.label_press.hidden=NO;
    }
}

- (void)emojiKeyBoardViewDidPressBackSpace:(AGEmojiKeyboardView *)emojiKeyBoardView {
    
}

- (UIColor *)randomColor {
    return [UIColor colorWithRed:drand48()
                           green:drand48()
                            blue:drand48()
                           alpha:drand48()];
}

- (UIImage *)randomImage {
    CGSize size = CGSizeMake(30, 10);
    UIGraphicsBeginImageContextWithOptions(size , NO, 0);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIColor *fillColor = [self randomColor];
    CGContextSetFillColorWithColor(context, [fillColor CGColor]);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    CGContextFillRect(context, rect);
    
    fillColor = [self randomColor];
    CGContextSetFillColorWithColor(context, [fillColor CGColor]);
    CGFloat xxx = 3;
    rect = CGRectMake(xxx, xxx, size.width - 2 * xxx, size.height - 2 * xxx);
    CGContextFillRect(context, rect);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (UIImage *)emojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView imageForSelectedCategory:(AGEmojiKeyboardViewCategoryImage)category {
    UIImage *img = [self randomImage];
    [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return img;
}

- (UIImage *)emojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView imageForNonSelectedCategory:(AGEmojiKeyboardViewCategoryImage)category {
    UIImage *img = [self randomImage];
    [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return img;
}

- (UIImage *)backSpaceButtonImageForEmojiKeyboardView:(AGEmojiKeyboardView *)emojiKeyboardView {
    UIImage *img = [self randomImage];
    [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    return img;
}

- (void)doClickIndex:(NSString*)text;
{
    int location = self.textView.selectedRange.location;
    NSString *content = self.textView.text;
    NSString *addValue=text;
    NSString *result = [NSString stringWithFormat:@"%@%@%@",
                        [content substringToIndex:location],
                        addValue,
                        [content substringFromIndex:location]];
    self.textView.text = result;
    
    if (self.textView.text.length > 0) {
        self.label_press.hidden=YES;
    } else {
        self.label_press.hidden=NO;
    }
    
    NSRange range;
    range.location = location+addValue.length;
    range.length = 0;//self.textView.text.length;
    self.textView.selectedRange = range;
}

#pragma mark -
#pragma mark SO
- (void)setRichText
{
    CGFloat top = 130;
    CGRect r = CGRectMake(0, top, self.myView.frame.size.width, 100);
    
    {
        //emoji
        face_view = [[AGFaceView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 216)];
        face_view.delegate_emjo=self;
        
        self.textView = [[UITextView alloc] initWithFrame:r];
        self.textView.delegate = self;
        self.textView.font=[UIFont systemFontOfSize:18];
        self.textView.keyboardType=UIKeyboardTypeTwitter;
        [self.base_scrollview addSubview:self.textView];
        
        //self.textView.inputView = emojiKeyboardView;
        //[[self.textView textInputMode] primaryLanguage]==@"emoji";
    }
    
    [self.textView becomeFirstResponder];
    {
        self.label_press = [[UILabel alloc] initWithFrame:CGRectMake(5, top, 150, 38)];
        self.label_press.font=[UIFont systemFontOfSize:18];
        self.label_press.backgroundColor=[UIColor clearColor];
        self.label_press.textColor=[UIColor grayColor];
        self.label_press.text=@"请输入评论信息...";
        [self.base_scrollview addSubview:self.label_press];
    }
    
    top = self.myView.frame.size.height-70;
    self.view_function = [[UIView alloc] initWithFrame:CGRectMake(0, top, self.view.frame.size.width, 50)];
    self.view_function.backgroundColor=[UIColor yellowColor];
    [self.view addSubview:self.view_function];
    
    //标记
    UIImageView * image_address = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"backviewreview.png"]];
    image_address.frame = CGRectMake(0, 0, 320, 50);
    [self.view_function addSubview:image_address];
    
    {
        self.label_address = [[UILabel alloc] initWithFrame:CGRectMake(self.myView.frame.size.width-60, 0, 50, 50)];
        self.label_address.backgroundColor=[UIColor clearColor];
        self.label_address.textColor=[UIColor grayColor];
        self.label_address.font=[UIFont systemFontOfSize:12];
        self.label_address.textAlignment=NSTextAlignmentRight;
        self.label_address.text=@"0/500";
        [self.view_function addSubview:self.label_address];
        
        /*
        self.label_select_photo = [[UILabel alloc] initWithFrame:CGRectMake(170, 0, 80, 50)];
        self.label_select_photo.backgroundColor=[UIColor clearColor];
        self.label_select_photo.textColor=[UIColor grayColor];
        self.label_select_photo.font=[UIFont systemFontOfSize:12];
        self.label_select_photo.text=@"没选择照片!";
        [self.view_function addSubview:self.label_select_photo];
        */
        //相册列表
        if (m_collectionView==nil) {
            UICollectionViewFlowLayout * layout= [[UICollectionViewFlowLayout alloc] init];
            [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
            [layout setItemSize:CGSizeMake(35, 35)]; //设置每个cell显示数据的宽和高必须
            layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 0);
            layout.minimumLineSpacing=5;
            layout.minimumInteritemSpacing=0;
            
            m_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(150, 0, 110, 50) collectionViewLayout:layout];
            m_collectionView.backgroundColor=[UIColor clearColor];
            m_collectionView.delegate=self;
            m_collectionView.dataSource=self;
            
            [m_collectionView registerClass:[AlbumAddImageCell class] forCellWithReuseIdentifier:@"ADD_GROUP_PICKER_CELL"];
            
            [self.view_function addSubview:m_collectionView];
        }
    }
    
    {
        //button...
        self.btn_click0 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.btn_click0.frame = CGRectMake(20, 5, 40, 40);
        self.btn_click0.tag=0;
        self.btn_click0.backgroundColor=[UIColor clearColor];
        [self.btn_click0 setImage:[UIImage imageNamed:@"carmerreview"] forState:UIControlStateNormal];
        [self.btn_click0 addTarget:self action:@selector(doClick:) forControlEvents:UIControlEventTouchDown];
        [self.view_function addSubview:self.btn_click0];
        
        //button...
        self.btn_click1 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.btn_click1.frame = CGRectMake(65, 5, 40, 40);
        self.btn_click1.tag=1;
        self.btn_click1.backgroundColor=[UIColor clearColor];
        [self.btn_click1 setImage:[UIImage imageNamed:@"libreview"] forState:UIControlStateNormal];
        [self.btn_click1 addTarget:self action:@selector(doClick:) forControlEvents:UIControlEventTouchDown];
        [self.view_function addSubview:self.btn_click1];
        
        //button...
        self.btn_click2 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.btn_click2.tag=2;
        self.btn_click2.frame = CGRectMake(110, 5, 40, 40);
        self.btn_click2.backgroundColor=[UIColor clearColor];
        [self.btn_click2 setImage:[UIImage imageNamed:@"facereview"] forState:UIControlStateNormal];
        [self.btn_click2 addTarget:self action:@selector(doClick:) forControlEvents:UIControlEventTouchDown];
        [self.view_function addSubview:self.btn_click2];
    }
    
    //键盘
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}

- (void)doClick:(UIButton*)sender
{
    if (sender.tag==0) {
        //拍照
        UIImagePickerControllerSourceType type;
        type = UIImagePickerControllerSourceTypeCamera;
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            type=UIImagePickerControllerSourceTypeCamera;
        } else {
            [self showAlertView:@"温馨提示" subtitle:@"改设备不支持拍照!"];
            return;
        }
        
        //[self.array_select removeAllObjects];
        //拍照
        SMImagePickerController * picker = [[SMImagePickerController alloc] init];
        picker.assetsLibrary = self.assetsLibrary;
        picker.array_select=self.array_select;
        picker.block_dismiss = ^(NSInteger code) {
            if (code == 0) {
                //[self.array_select removeAllObjects];
            } else {
                NSLog(@"选择照片了!");
            }
            //NSString * str_select = [NSString stringWithFormat:@"选择了%d张照片", [self.array_select count]];
            //self.label_select_photo.text=str_select;
            [m_collectionView reloadData];
        };
        [self presentViewController:picker animated:YES completion:nil];
    }
    if (sender.tag==1) {
        //[self.array_select removeAllObjects];
        
        SMAlbumViewController * vc = [[SMAlbumViewController alloc] init];
        vc.assetsLibrary = self.assetsLibrary;
        vc.array_assert=self.array_assert;
        vc.array_select=self.array_select;
        if (self.m_b_have_load_img) {
            self.m_b_have_load_img=YES;
            vc.m_b_have_load_img = YES;
        } else {
            vc.m_b_have_load_img = NO;
            self.m_b_have_load_img=YES;
        }
        vc.block_dismiss=^(NSInteger code) {
            if (code == 0) {
                //[self.array_select removeAllObjects];
            } else {
                NSLog(@"选择照片了!");
            }
            //NSString * str_select = [NSString stringWithFormat:@"选择了%d张照片", [self.array_select count]];
            //self.label_select_photo.text=str_select;
            [m_collectionView reloadData];
        };
        [self presentViewController:vc animated:YES completion:nil];
    }
    if (sender.tag==2) {
        //[self.textView resignFirstResponder];
        if (self.textView.inputView==nil) {
            self.textView.inputView = face_view;
        } else {
            self.textView.inputView=nil;
        }
        [self.textView reloadInputViews];
    }
}
#pragma mark -
#pragma mark UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    //self.view_for_face.hidden=NO;
    
    {
        NSInteger offset = self.view.frame.size.height - IOS_IPHONE_TXT_HEIGHT-50;
        CGFloat top = 130;
        if ([[UIDevice currentDevice].systemVersion doubleValue] < 7.0) {
            offset=offset-20;
        }
        [UIView beginAnimations:@"anim" context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.1];
        self.view_function.frame=CGRectMake(0, offset, self.myView.frame.size.width, 50);
        
        CGFloat hei = abs(offset-top-60);
        if (hei < 100) {
            hei = 100;
        }
        self.textView.frame=CGRectMake(0, top, self.myView.frame.size.width, hei);
        [UIView commitAnimations];
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.view_for_face.hidden=YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 0) {
        self.label_press.hidden=YES;
    } else {
        self.label_press.hidden=NO;
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
{
    NSString * temp = [textView.text stringByReplacingCharactersInRange:range withString:text];
    {
        NSString * str_info = [NSString stringWithFormat:@"%d/500", temp.length];
        self.label_address.text=str_info;
    }
    if (temp.length > 500) {
        textView.text = [temp substringToIndex:500];
        return NO;
    }
    return YES;
}

-(void)keyboardWillShow:(NSNotification *)notification
{
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_2
        NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
#else
        NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey];
#endif
        CGRect keyboardBounds;
        [keyboardBoundsValue getValue:&keyboardBounds];
        NSInteger offset = keyboardBounds.origin.y-50;//self.view.frame.size.height-keyboardBounds.origin.y-48.0;
        //CGRect listFrame = CGRectMake(0, -offset, self.view.frame.size.width,self.view.frame.size.height);
        NSLog(@"offset is %f",keyboardBounds.origin.y);
        CGFloat top = 130;
        
        if ([[UIDevice currentDevice].systemVersion doubleValue] < 7.0) {
            offset=offset-20;
        }
        
        [UIView beginAnimations:@"anim" context:NULL];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.1];
        //处理移动事件，将各视图设置最终要达到的状态
        
        //self.view.frame=listFrame;
        self.view_function.frame=CGRectMake(0, offset, self.myView.frame.size.width, 50);
        
        CGFloat hei = abs(offset-top-60);
        if (hei < 100) {
            hei = 100;
        }
        self.textView.frame=CGRectMake(0, top, self.myView.frame.size.width, hei);
        
        [UIView commitAnimations];
    }
}

#pragma mark -
#pragma mark UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
{
    return [self.array_select count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    AlbumAddImageCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ADD_GROUP_PICKER_CELL" forIndexPath:indexPath];
    
    // load the image for this cell
    if (indexPath.row < [self.array_select count]) {
        ALAsset * object = [self.array_select objectAtIndex:indexPath.row];
        cell.image_thumb.image = [UIImage imageWithCGImage:object.thumbnail];
    } else {
        cell.image_thumb.image = [UIImage imageNamed:@"album_add_image.png"];
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    ALbumFooter *footer = nil;
    if([kind isEqual:UICollectionElementKindSectionFooter]){
        footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                    withReuseIdentifier:@"ALbumAddImageFooter"
                                                           forIndexPath:indexPath];
        if ([self.array_select count]>16) {
            footer.label_num.text = [NSString stringWithFormat:@"%d张照片", [self.array_select count]];
        }
        //album_add_image@2x
    } else if([kind isEqual:UICollectionElementKindSectionHeader]) {
        ALbumHeader * header = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                  withReuseIdentifier:@"ALbumHeader"
                                                                         forIndexPath:indexPath];
        return header;
    }
    return footer;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
    NSLog(@"select index:%d", indexPath.row);
}



@end

















